import React, { useCallback, useEffect, useState } from 'react';

import { Button, Card, Form, Input, message, Modal, Select, Tooltip } from 'antd';
import { history } from 'umi'

import { BottomAction } from '@/components';
import Icon from '@/components/IconPro';
import LabelValue from '@/components/LabelValue';
import LimitInput from '@/components/LimitInput';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { defaultFormatResult, useRequest } from '@/hooks';
import {
    editEntryMaterial,
    fetchEntryMaterialById,
    fetchEntrySettingTemplateDictionary,
    fetchOrgList
} from '@/pages/TurnoverSetting/EntrySetting/services';
import { formatResultByFetchDetail } from '@/pages/TurnoverSetting/EntrySetting/util';
import pageTabUtil from '@/utils/pageTabUtil';

import Table from '../../components/DynamicTable';
import styles from './index.less';

const { Option } = Select;

/**
 * 入职材料模板
 * @param {*} param0
 * @returns
 */
const EntryMaterialEdit = ({ form, location }) => {
    const [selectedElectronMaterials, setSelectedElectronMaterials] = useState([]);
    const [selectedEntityMaterials, setSelectedEntityMaterials] = useState([]);
    const [selectedOrg, setSelectedOrg] = useState([]);
    const [tempSelectedOrg, setTempSelectedOrg] = useState([]);
    const [visibleModal, setVisibleModal] = useState(false);
    const { query } = location;
    const { id = '' } = query;
    const { getFieldDecorator } = form;
    const currentUser = JSON.parse(localStorage.getItem('user') || {});
    const { administrativeOrganizationCode } = currentUser || {};

    /**
     * 获取电子材料
     */
    const { run: getElectronMaterialDictionary, data: electronMaterialDictionary } = useRequest(
        country =>
            fetchEntrySettingTemplateDictionary({
                countryNameCode: country,
                code: 'electronMaterial'
            }),
        {
            manual: true,
            formatResult: formatResultByFetchDetail
        }
    );

    /**
     * 获取实体材料
     */
    const { run: getEntityMaterialDictionary, data: entityMaterialDictionary } = useRequest(
        country =>
            fetchEntrySettingTemplateDictionary({
                countryNameCode: country,
                code: 'entityMaterial'
            }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    // 获取机构列表
    const { data: orgDataSource } = useRequest(fetchOrgList, {
        ...defaultFormatResult
    });

    // 根据ID获取模板信息
    const { run: getEditEntryMaterialsById, data: materialsDataSource, loading: getDataLoading } = useRequest(
        params => fetchEntryMaterialById(params),
        {
            manual: true,
            formatResult: formatResultByFetchDetail
        }
    );

    const { run: runEditEntryMaterial, loading } = useRequest(params => editEntryMaterial(params), {
        manual: true
    });

    const { settingName, tipInfo, administrativeScopes = [], electronMaterials = [], entityMaterials } =
        materialsDataSource || {};

    /**
     * 通过机构code获取对应的国家编号
     */
    const getCountryNameCodeByOrganizationCode = useCallback(
        organizationCode => orgDataSource?.find(item => item.organizationCode === organizationCode)?.countryNameCode,
        [orgDataSource]
    );

    // 获取模板信息
    useEffect(() => {
        if (id) {
            getEditEntryMaterialsById(id);
        }
    }, [getEditEntryMaterialsById, id]);

    // 功能为添加入职材料模板时默认选中当前用户所处的机构
    useEffect(() => {
        if (!id && administrativeOrganizationCode) {
            const countryNameCode = getCountryNameCodeByOrganizationCode(administrativeOrganizationCode);
            setSelectedOrg([administrativeOrganizationCode]);
            setTempSelectedOrg([administrativeOrganizationCode]);
            getElectronMaterialDictionary(countryNameCode);
            getEntityMaterialDictionary(countryNameCode);
        }
    }, [
        administrativeOrganizationCode,
        getCountryNameCodeByOrganizationCode,
        getElectronMaterialDictionary,
        getEntityMaterialDictionary,
        id
    ]);

    // 初始化材料列表
    useEffect(() => {
        // 过滤出已选中的材料列表
        const initialSelectMaterials = (materials = [], fieldName) =>
            materials.map((material, index) => ({ row: index, material: material[fieldName] }));

        if (materialsDataSource) {
            const electronResult = initialSelectMaterials(materialsDataSource?.electronMaterials || [], 'materialCode');
            const entityResult = initialSelectMaterials(materialsDataSource?.entityMaterials || [], 'materialCode');

            // 初始化已选择的电子材料及实体材料
            setSelectedElectronMaterials(electronResult);
            setSelectedEntityMaterials(entityResult);

            // 初始化已选择的行政机构
            setSelectedOrg(materialsDataSource?.administrativeScopes || []);
            setTempSelectedOrg(materialsDataSource?.administrativeScopes || []);

            // 根据已选中的行政机构获取电子材料及实体材料字典
            if (
                Array.isArray(materialsDataSource?.administrativeScopes) &&
                materialsDataSource?.administrativeScopes.length
            ) {
                const countryNameCode = getCountryNameCodeByOrganizationCode(
                    materialsDataSource?.administrativeScopes[0]
                );

                const { isDefault } = materialsDataSource;
                if (countryNameCode) {
                    getElectronMaterialDictionary(isDefault === 1 ? null : countryNameCode);
                    getEntityMaterialDictionary(isDefault === 1 ? null : countryNameCode);
                }
            }
        }
    }, [
        getCountryNameCodeByOrganizationCode,
        getElectronMaterialDictionary,
        getEntityMaterialDictionary,
        materialsDataSource
    ]);

    // 过滤已选中的实体材料项
    const filterEntityMaterials = (material, row, remove) => {
        const result = selectedEntityMaterials.filter(item => item.row !== row);
        if (remove) {
            setSelectedEntityMaterials([...result]);
        } else {
            setSelectedEntityMaterials([...result, { row, material }]);
        }
    };

    // 过滤已选中的电子材料项
    const filterElectronMaterials = (material, row, remove) => {
        const result = selectedElectronMaterials.filter(item => item.row !== row);
        if (remove) {
            setSelectedElectronMaterials([...result]);
        } else {
            setSelectedElectronMaterials([...result, { row, material }]);
        }
    };

    const getObjectArrayValue = (materials = [], fieldName) => materials.map(item => item[fieldName]);

    const filterMaterialsFromDictionary = (materials, materialsType) => {
        const materialsDictionary =
            materialsType === 'electron' ? electronMaterialDictionary : entityMaterialDictionary;
        return materialsDictionary
            .map(item => {
                const { dictName, properties, remark, dictValue } = item;
                const { inputType, uploadTip, uploadFormatTip, uploadCountLimit, uploadFormatLimit } = properties || {};
                if (materials.includes(dictValue)) {
                    return {
                        materialCode: dictValue,
                        materialName: dictName,
                        inputType,
                        uploadTip,
                        uploadFormatTip,
                        uploadCountLimit,
                        uploadFormatLimit,
                        remark
                    };
                }
                return null;
            })
            .filter(Boolean);
    };

    /**
     * 提交
     */
    const handleClick = () => {
        form.validateFields(async (errors, value) => {
            if (!errors) {
                const electronValue = getObjectArrayValue(value.electronMaterials, 'materialName');
                const entityValue = getObjectArrayValue(value.entityMaterials, 'materialName');
                const selectElectronMaterials = filterMaterialsFromDictionary(electronValue, 'electron');
                const selectEntityMaterials = filterMaterialsFromDictionary(entityValue, 'entity');
                const obj = {
                    isDefault: materialsDataSource?.isDefault ?? 0,
                    administrativeScopes: [].concat(value.administrativeScopes),
                    electronMaterials: selectElectronMaterials,
                    entityMaterials: selectEntityMaterials,
                    settingName: value.settingName,
                    tipInfo: value.tipInfo || ''
                };
                if (id) {
                    obj.id = id;
                }

                const result = await runEditEntryMaterial(obj);
                const { code, msg } = result;
                if (code === 10000) {
                    message.success('提交成功');
                    history.push({
                        pathname: '/office/personnelManagement/onboardAndLeave/setting/index',
                        state: { tabRoute: true, tabRefresh: true, closeTab: true }
                    });
                } else if (code === 21008) {
                    // 配置已变更, 当前访问的数据是旧数据, 要返回列表并刷新列表
                    message.warning(msg);
                    history.push({
                        pathname: '/office/personnelManagement/onboardAndLeave/setting/index',
                        state: { tabRoute: true, tabRefresh: true, closeTab: true }
                    });
                } else {
                    message.error(`提交失败: ${msg}`);
                }
            }
        });
    };

    const electronMaterialsColumns = [
        {
            title: '名称',
            dataIndex: 'materialCode',
            render: ({ fieldDecorator, text, recordKey }) => (
                <React.Fragment>
                    {fieldDecorator('materialName', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '材料名称不能为空'
                            }
                        ]
                    })(
                        <Select
                            style={{ width: 200 }}
                            onChange={value => {
                                filterElectronMaterials(value, recordKey);
                            }}
                        >
                            {selectedOrg.length &&
                                electronMaterialDictionary?.map(item => {
                                    const { dictName, dictValue } = item;
                                    return (
                                        <Option
                                            key={id}
                                            value={dictValue}
                                            disabled={selectedElectronMaterials.find(
                                                d => d.material === item.dictValue
                                            )}
                                        >
                                            {dictName}
                                        </Option>
                                    );
                                })}
                        </Select>
                    )}
                </React.Fragment>
            )
        },
        {
            title: '信息录入方式',
            dataIndex: 'inputType',
            render: ({ getFieldValue }) => {
                const materialName = getFieldValue('materialName');
                const materialInputType = electronMaterialDictionary?.find(item => item.dictValue === materialName)
                    ?.properties?.inputType;

                if (typeof materialInputType === 'number') {
                    return <span>{materialInputType ? '附件上传' : '文本录入'}</span>;
                }

                return <span>--</span>;
            }
        },
        {
            title: '提示信息',
            dataIndex: 'uploadTip',
            render: ({ text, fieldDecorator, getFieldValue }) => {
                const materialName = getFieldValue('materialName');
                const materialUploadTip = electronMaterialDictionary?.find(item => item.dictValue === materialName)
                    ?.properties?.uploadTip;

                return (
                    <React.Fragment>
                        {text ? (
                            fieldDecorator('uploadTip', {
                                initialValue: materialUploadTip,
                                rules: [
                                    {
                                        required: true,
                                        message: '不能为空'
                                    }
                                ]
                            })(<Input style={{ width: '100%' }} maxLength={200} />)
                        ) : (
                            <span>--</span>
                        )}
                    </React.Fragment>
                );
            }
        },
        {
            title: '操作',
            dataIndex: 'controls',
            width: 100,
            render: ({ index, methods, getFieldValue, recordKey }) => (
                <Tooltip placement="top" title="删除">
                    <Icon.Button
                        className={styles.fontSize22}
                        dark
                        icon="iconlistfunction_delete_icon_default"
                        onClick={() => {
                            const materialName = getFieldValue('materialName');
                            filterElectronMaterials(materialName, recordKey, true);
                            methods.remove(index);
                        }}
                    />
                </Tooltip>
            )
        }
    ];

    const entityMaterialsColumns = [
        {
            title: '名称',
            dataIndex: 'materialCode',
            render: ({ fieldDecorator, text, recordKey }) => (
                <React.Fragment>
                    {fieldDecorator('materialName', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '材料名称不能为空'
                            }
                        ]
                    })(
                        <Select
                            style={{ width: 200 }}
                            onChange={value => {
                                filterEntityMaterials(value, recordKey);
                            }}
                        >
                            {selectedOrg.length &&
                                entityMaterialDictionary?.map(item => {
                                    const { dictName, dictValue } = item;
                                    return (
                                        <Option
                                            key={id}
                                            value={dictValue}
                                            disabled={selectedEntityMaterials.find(d => d.material === item.dictValue)}
                                        >
                                            {dictName}
                                        </Option>
                                    );
                                })}
                        </Select>
                    )}
                </React.Fragment>
            )
        },
        {
            title: '上传数量',
            dataIndex: 'uploadCountLimit',
            render: ({ getFieldValue }) => {
                const materialName = getFieldValue('materialName');
                const materialCount = entityMaterialDictionary?.find(item => item.dictValue === materialName)
                    ?.properties?.uploadCountLimit;
                return <span>{materialCount || '--'}</span>;
            }
        },
        {
            title: '操作',
            dataIndex: 'controls',
            width: 100,
            render: ({ index, methods, getFieldValue, recordKey }) => (
                <Tooltip placement="top" title="删除">
                    <Icon.Button
                        className={styles.fontSize22}
                        dark
                        icon="iconlistfunction_delete_icon_default"
                        onClick={() => {
                            const materialName = getFieldValue('materialName');
                            filterEntityMaterials(materialName, recordKey, true);
                            methods.remove(index);
                        }}
                    />
                </Tooltip>
            )
        }
    ];

    /**
     * 根据用户选择适用的行政机构获取电子材料列表和实体材料列表
     */
    const handleAdministrativeScopesSelected = value => {
        const countryNameCode = getCountryNameCodeByOrganizationCode(value);
        getElectronMaterialDictionary(countryNameCode);
        getEntityMaterialDictionary(countryNameCode);
    };

    /**
     * 行政机构变更时的回调函数
     * 如果当前没有选中任何机构则不弹窗
     * 采用两个变量存储用户选中的值以便进行数据交换
     * 如果未选中需要任何机构需要初始化selectOrg
     */
    const handleAdministrativeScopesChanged = value => {
        if (tempSelectedOrg.length) {
            setVisibleModal(true);
        } else {
            setSelectedOrg(value);
        }
        setTempSelectedOrg(value);
    };

    /**
     * 取消采用selectOrg中的值
     */
    const handleModalCancel = () => {
        setTempSelectedOrg(selectedOrg);
        setVisibleModal(false);
        form.setFieldsValue({ administrativeScopes: selectedOrg });
    };

    /**
     * OK采用tempSelectedOrg中的值
     */
    const handleModalOk = () => {
        setSelectedOrg(tempSelectedOrg);
        setVisibleModal(false);
        setSelectedElectronMaterials([]);
        setSelectedEntityMaterials([]);
        form.setFieldsValue({ administrativeScopes: tempSelectedOrg, electronMaterials: [], entityMaterials: [] });
    };

    const isDefault = materialsDataSource?.isDefault;

    return (
        <PageHeaderWrapper>
            <Card
                title={`${id ? '编辑' : '新增'}模板`}
                bordered={false}
                loading={getDataLoading}
                className={styles.entryCard}
                extra={
                    <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                        <Button type="primary" onClick={handleClick} loading={loading}>
                            提交
                        </Button>
                    </BottomAction>
                }
            >
                <div className={styles.entryMaterialEditWrapper}>
                    <LabelValue
                        label="配置名称"
                        labelClassName={styles.labelWidth110}
                        requiredMark
                        value={() => (
                            <Form.Item>
                                {getFieldDecorator('settingName', {
                                    initialValue: settingName,
                                    rules: [{ required: true, message: '请输入配置名称' }]
                                })(<Input style={{ width: 530 }} maxLength={200} />)}
                            </Form.Item>
                        )}
                    />
                    <LabelValue
                        label="适用行政机构"
                        labelClassName={styles.labelWidth110}
                        requiredMark
                        value={() => (
                            <Form.Item>
                                {isDefault === 1 && '全集团'}
                                {isDefault === 1 &&
                                    form.getFieldDecorator('administrativeScopes', {
                                        initialValue: administrativeScopes || undefined
                                    })(<input type="hidden" />)}
                                {isDefault !== 1 &&
                                    getFieldDecorator('administrativeScopes', {
                                        initialValue: id ? administrativeScopes : administrativeOrganizationCode,
                                        rules: [{ required: true, message: '请选择行政机构' }]
                                    })(
                                        <Select
                                            mode="multiple"
                                            style={{ width: 530 }}
                                            placeholder="请选择适用行政机构"
                                            onSelect={handleAdministrativeScopesSelected}
                                            onChange={handleAdministrativeScopesChanged}
                                            filterOption={(inputValue, option) =>
                                                option.props.children.includes(inputValue.trim())
                                            }
                                        >
                                            {orgDataSource?.map(org => {
                                                const { organizationCode, organizationName, countryNameCode } = org;

                                                return (
                                                    <Option
                                                        key={organizationCode}
                                                        value={organizationCode}
                                                        disabled={
                                                            selectedOrg.length &&
                                                            countryNameCode !==
                                                                orgDataSource.find(
                                                                    item => item.organizationCode === selectedOrg[0]
                                                                )?.countryNameCode
                                                        }
                                                    >
                                                        {organizationName}
                                                    </Option>
                                                );
                                            })}
                                        </Select>
                                    )}
                            </Form.Item>
                        )}
                    />
                    <LabelValue
                        label="电子材料列表"
                        labelClassName={styles.labelWidth110}
                        requiredMark
                        align="top"
                        value={() => (
                            <Table
                                className={styles.materialTable}
                                style={{ width: 720 }}
                                form={form}
                                rules={[{ required: true, type: 'array', message: '请填写电子材料列表' }]}
                                fieldName="electronMaterials"
                                columns={electronMaterialsColumns}
                                initialValue={electronMaterials}
                            />
                        )}
                    />
                    <LabelValue
                        label="实体材料列表"
                        labelClassName={styles.labelWidth110}
                        requiredMark
                        align="top"
                        value={() => (
                            <Table
                                className={styles.materialTable}
                                style={{ width: 720 }}
                                form={form}
                                rules={[{ required: true, type: 'array', message: '请填实体材料列表' }]}
                                fieldName="entityMaterials"
                                columns={entityMaterialsColumns}
                                initialValue={entityMaterials}
                            />
                        )}
                    />
                    <LabelValue
                        label="材料提供提示"
                        labelClassName={styles.labelWidth110}
                        align="top"
                        value={() => (
                            <Form.Item>
                                {getFieldDecorator('tipInfo', {
                                    initialValue: tipInfo,
                                    rules: [
                                        {
                                            min: 0,
                                            max: 4000
                                        }
                                    ]
                                })(
                                    <LimitInput
                                        style={{ width: 720 }}
                                        placeholder="请输入提示信息"
                                        autoSize={{ minRows: 4, maxRows: 8 }}
                                        area
                                        maxLength={4000}
                                    />
                                )}
                            </Form.Item>
                        )}
                    />
                </div>
            </Card>
            <Modal
                visible={visibleModal}
                className={styles.orgChangedModal}
                closable={false}
                maskClosable={false}
                width={480}
                onCancel={handleModalCancel}
                onOk={handleModalOk}
            >
                <div className={styles.orgChangedModalBody}>
                    <Icon type="exclamation-circle" theme="filled" />
                    <div>
                        <p>适用行政机构与配置内容相关联，确定修改？</p>
                        <span>修改后将清空配置内容</span>
                    </div>
                </div>
            </Modal>
        </PageHeaderWrapper>
    );
};

export default Form.create()(EntryMaterialEdit);
